//
//  ZBShareMenuView.m
//  MessageDisplay
//
//  Created by zhoubin@moshi on 14-5-13.
//  Copyright (c) 2014年 Crius_ZB. All rights reserved.
//

#import "PhotoListView.h"
#import "UIView+BaseFramework.h"
#import "NSString+BaseFramework.h"
#import "PhotoEntity.h"
#import "TipHandler.h"
#import "MWGridCell.h"


#define kPhotoItemWidth 70

@interface PhotoListView ()
{

    UIActionSheet *_myActionSheet;
    UILabel       *_tipLabel;

}

@property(nonatomic, strong) UIScrollView *photoScrollView;
@property(nonatomic, weak) UIScrollView   *shareMenuScrollView;

@property(nonatomic, strong) UINavigationController *photoBrowserNavigationController;
@property(nonatomic, strong)UIImagePickerController *picker;

@end

@implementation PhotoListView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self setup];
    }
    return self;
}

- (void)setup
{

    self.isEditing           = NO;
    self.selectedPhotoMArray = [NSMutableArray array];

    self.backgroundColor = [UIColor colorWithRed:248.0f / 255
                                           green:248.0f / 255
                                            blue:255.0f / 255
                                           alpha:1.0];

    _photoScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.width, self.height - 30)];
    _photoScrollView.contentSize      = CGSizeMake(_photoScrollView.width, _photoScrollView.height);
    _photoScrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self addSubview:_photoScrollView];

    _tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, _photoScrollView.bottom, self.width - 100, 20)];
    _tipLabel.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    [self addSubview:_tipLabel];

    [self reloadPhotoItemView:self.selectedPhotoMArray];

    [self loadAssets];


}

- (void)reloadDataWithImage:(UIImage *)image
{
    NSString *fileId = nil;

    fileId = [NSString stringWithFormat:@"%.0f",
                                        [[NSDate date] timeIntervalSince1970]];

    NSString *fileName = [NSString filePathInDocumentWithFileName:fileId];


//    [self writeImage:image
//          toFilePath:fileName];

    PhotoEntity *photoEntity = [[PhotoEntity alloc] init];
    photoEntity.imageId        = fileId;
    photoEntity.imageUrlString = fileName;
    photoEntity.image          = image;

    [self.selectedPhotoMArray addObject:photoEntity];

    [self reloadPhotoItemView:self.selectedPhotoMArray];
}

- (void)reloadPhotoItemView:(NSArray *)imageList
{
    [self.photoScrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

    self.itemViewMArray = [NSMutableArray array];
    for (NSUInteger i = 0; i < imageList.count; i++)
    {

        PhotoEntity *photoEntity = [imageList objectAtIndex:i];

        PhotoItemView *photoItem = [[PhotoItemView alloc] initWithFrame:CGRectMake(0,
                                                                                   0,
                                                                                   kPhotoItemWidth,
                                                                                   kPhotoItemWidth)];
        photoItem.photo     = photoEntity;
        photoItem.delegate  = self;
        photoItem.index     = i;
        photoItem.isEditing = self.isEditing;

        [self.itemViewMArray addObject:photoItem];
    }
	
	if (self.itemViewMArray.count == 0 && self.isEditing) {
		self.isEditing = NO;
	}


    int photoCount = self.itemViewMArray.count;
	if (!self.isEditing && self.selectedPhotoMArray.count < (self.maxSelectedCount == 0 ?100:self.maxSelectedCount))
    {
        UIButton *addPhotoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [addPhotoBtn setFrame:CGRectMake(0,
                                         0,
                                         kPhotoItemWidth,
                                         kPhotoItemWidth)];//
        [addPhotoBtn setImage:[UIImage imageNamed:@"add_photo_button"]
                     forState:UIControlStateNormal];
        [addPhotoBtn setImage:[UIImage imageNamed:@"add_photo_button"]
                     forState:UIControlStateHighlighted];
        //给添加按钮加点击事件
        [addPhotoBtn addTarget:self
                        action:@selector(showPhotoMenu)
              forControlEvents:UIControlEventTouchUpInside];

        [self.itemViewMArray addObject:addPhotoBtn];

    }

    if (imageList.count >= 1)
    {
        UIButton *showDeletePhotoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [showDeletePhotoBtn setFrame:CGRectMake(20 + (self.photoScrollView.height - 10 + 5) * self.photoScrollView.subviews.count,
                                                5,
                                                kPhotoItemWidth,
                                                kPhotoItemWidth)];//
        [showDeletePhotoBtn setImage:[UIImage imageNamed:@"delete_photo_button"]
                            forState:UIControlStateNormal];
        [showDeletePhotoBtn setImage:[UIImage imageNamed:@"delete_photo_button"]
                            forState:UIControlStateHighlighted];
        //给添加按钮加点击事件
        [showDeletePhotoBtn addTarget:self
                               action:@selector(showPhotoDeleteBtnClick)
                     forControlEvents:UIControlEventTouchUpInside];
        [self.itemViewMArray addObject:showDeletePhotoBtn];
    }

    CGSize oldSize = self.photoScrollView.contentSize;

    self.photoScrollView.contentSize = CGSizeMake(self.scrollView.width, ceil(self.itemViewMArray.count / 4.0) * 70);;

    if ([self.delegate respondsToSelector:@selector(photoContentChangeWithNewSize:oldSize:)])
    {
        [self.delegate photoContentChangeWithNewSize:self.photoScrollView.contentSize
                                             oldSize:oldSize];
    }

    for (int j = 0; j < self.itemViewMArray.count; ++j)
    {

        UIView  *view = [self.itemViewMArray objectAtIndex:j];
        CGPoint point;
        point.y = j / 4 * (kPhotoItemWidth) + 10;
        point.x = (j % 4) * (kPhotoItemWidth) + 10;

        CGRect rect = view.frame;
        rect.origin = point;

        view.frame = rect;

        [self.photoScrollView addSubview:view];

    }
	
	if (self.maxSelectedCount != 0)
	{
	 _tipLabel.text = [NSString stringWithFormat:@"已选%d张，共可选%d张",
					   photoCount,self.maxSelectedCount];
	}
	else
	{
		_tipLabel.text = [NSString stringWithFormat:@"已选%d张",photoCount];
	}

}
- (void)setMaxSelectedCount:(int)maxSelectedCount
{
	_maxSelectedCount = maxSelectedCount;
	
	if (self.maxSelectedCount != 0)
	{
	 _tipLabel.text = [NSString stringWithFormat:@"已选%d张，共可选%d张",
					   self.selectedPhotoMArray.count,self.maxSelectedCount];
	}
	else
	{
		_tipLabel.text = [NSString stringWithFormat:@"已选%d张",self.selectedPhotoMArray.count];
	}
	
}
- (void)showPhotoDeleteBtnClick
{
    self.isEditing = !self.isEditing;

    for (UIView *photoItemView  in self.photoScrollView.subviews)
    {

        if ([photoItemView isKindOfClass:[PhotoItemView class]])
        {
            ((PhotoItemView *) photoItemView).isEditing = self.isEditing;
        }
    }

    [self reloadData];

}

- (void)showPhotoMenu
{
    //在这里呼出下方菜单按钮项
    _myActionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                 delegate:self
                                        cancelButtonTitle:@"取消"
                                   destructiveButtonTitle:nil
                                        otherButtonTitles:@"打开照相机",
                                                          @"从手机相册获取",
                                                          nil];
    //刚才少写了这一句
    [_myActionSheet showInView:self.window];


}

//下拉菜单的点击响应事件
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{

    if (buttonIndex == _myActionSheet.cancelButtonIndex)
    {
        NSLog(@"取消");
    }
    switch (buttonIndex)
    {
        case 0:
            [self takePhoto];
            break;
        case 1:
            [self localPhoto];
            break;
        default:
            break;
    }
}

//开始拍照
- (void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
		if (!self.picker)
		{
			self.picker = [[UIImagePickerController alloc] init];
			self.picker.delegate      = self;
			//设置拍照后的图片可被编辑
			self.picker.allowsEditing = YES;
			self.picker.sourceType    = sourceType;
		}

        id <PhotoListViewDelegate> o = self.delegate;
        if ([o respondsToSelector:@selector(addPicker:)])
        {
            [o addPicker:self.picker];
        }
    }
    else
    {
        NSLog(@"模拟其中无法打开照相机,请在真机中使用");
    }
}

/*
    新加的另外的方法
 */
////////////////////////////////////////////////////////////
//打开相册，可以多选
- (void)localPhoto
{
    NSMutableArray *copy   = [_assets copy];
    NSMutableArray *photos = [NSMutableArray array];
    NSMutableArray *thumbs = [NSMutableArray array];

    for (ALAsset   *asset in copy)
    {
        [photos addObject:[MWPhoto photoWithURL:asset.defaultRepresentation.url]];
        [thumbs addObject:[MWPhoto photoWithImage:[UIImage imageWithCGImage:asset.thumbnail]]];
    }

    self.photos             = photos;
    self.thumbs             = thumbs;

    // Reset selections
    {
        _selections = [NSMutableArray new];
        for (int i = 0; i < photos.count; i++)
        {
            [_selections addObject:[NSNumber numberWithBool:NO]];
        }
    }
    // Create browser
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.displayActionButton     = NO;
    browser.displayNavArrows        = YES;
    browser.displaySelectionButtons = YES;
    browser.alwaysShowControls      = YES;
    browser.zoomPhotosToFill        = YES;
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
    browser.wantsFullScreenLayout = YES;
#endif
    browser.enableGrid           = YES;
    browser.startOnGrid          = YES;
    browser.enableSwipeToDismiss = YES;
    [browser setCurrentPhotoIndex:0];




    // Modal
    self.photoBrowserNavigationController = [[UINavigationController alloc] initWithRootViewController:browser];
    self.photoBrowserNavigationController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    id <PhotoListViewDelegate> delegateController = self.delegate;
    if ([delegateController respondsToSelector:@selector(addPicker:)])
    {
        [delegateController addUIImagePicker:self.photoBrowserNavigationController];
    }
}


//选择某张照片之后
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{

    //关闭相册界面
    [picker dismissViewControllerAnimated:YES
                               completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        [self reloadDataWithImage:image];

    }
}

- (void)writeImage:(UIImage *)image toFilePath:(NSString *)fileName
{
    if ([NSString isExistsFile:fileName])
    {
        return;
    }

    NSData *datas;
    if (UIImagePNGRepresentation(image) == nil)
    {
        datas = UIImageJPEGRepresentation(image, 1.0);
    }
    else
    {
        datas = UIImagePNGRepresentation(image);
    }

    [datas writeToFile:fileName
            atomically:YES];


}
- (NSMutableArray *)selectedPhotoMArray
{
	if (!_selectedPhotoMArray) 
	{
		_selectedPhotoMArray = [[NSMutableArray alloc] init];
	}
	return _selectedPhotoMArray;
}

- (void)reloadData
{
    [self reloadPhotoItemView:self.selectedPhotoMArray];
}

- (void)dealloc
{
    //self.shareMenuItems = nil;
    self.photoScrollView.delegate     = self;
    self.shareMenuScrollView.delegate = self;
    self.shareMenuScrollView          = nil;
}

#pragma mark - MessagePhotoItemDelegate

- (void)photoItemView:(PhotoItemView *)photoItem
{
    [self.selectedPhotoMArray removeObjectAtIndex:(NSUInteger) photoItem.index];
    [self reloadPhotoItemView:self.selectedPhotoMArray];
}

#pragma mark - MWPhotoBrowserDelegate

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser
{
    return _photos.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index
{
    if (index < _photos.count)
    {
        return [_photos objectAtIndex:index];
    }
    return nil;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser thumbPhotoAtIndex:(NSUInteger)index
{
    if (index < _thumbs.count)
    {
        return [_thumbs objectAtIndex:index];
    }
    return nil;
}

//- (MWCaptionView *)photoBrowser:(MWPhotoBrowser *)photoBrowser captionViewForPhotoAtIndex:(NSUInteger)index {
//    MWPhoto *photo = [self.photos objectAtIndex:index];
//    MWCaptionView *captionView = [[MWCaptionView alloc] initWithPhoto:photo];
//    return [captionView autorelease];
//}

//- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser actionButtonPressedForPhotoAtIndex:(NSUInteger)index {
//    NSLog(@"ACTION!");
//}

- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser didDisplayPhotoAtIndex:(NSUInteger)index
{
    NSLog(@"Did start viewing photo at index %lu", (unsigned long) index);
}

- (BOOL)photoBrowser:(MWPhotoBrowser *)photoBrowser isPhotoSelectedAtIndex:(NSUInteger)index
{
    return [[_selections objectAtIndex:index] boolValue];
}

//- (NSString *)photoBrowser:(MWPhotoBrowser *)photoBrowser titleForPhotoAtIndex:(NSUInteger)index {
//    return [NSString stringWithFormat:@"Photo %lu", (unsigned long)index+1];
//}

- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index selectedChanged:(BOOL)selected
{
	__block int count = 0;
	[_selections enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
		if ([obj boolValue])
		{
			count ++;
		}
	}];
	
	if (count + self.selectedPhotoMArray.count == self.maxSelectedCount && selected)
	{
		[photoBrowser reloadData];
		if (photoBrowser.gridViewController)
		{
			MWGridCell *cell = (MWGridCell *)[photoBrowser.gridViewController.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:index
																													  inSection:0]];
			cell.isSelected = NO; 
			
			
		}
		[TipHandler showAlert:[NSString stringWithFormat: @"最多可以选择%d张！",self.maxSelectedCount - self.selectedPhotoMArray.count]];
	}
	else
	{		
		[_selections replaceObjectAtIndex:index
							   withObject:[NSNumber numberWithBool:selected]];
		NSLog(@"Photo at index %lu selected %@", (unsigned long) index, selected ? @"YES" : @"NO");
	}

}

- (void)photoBrowserDidFinishModalPresentation:(MWPhotoBrowser *)photoBrowser
{
    // If we subscribe to this method we must dismiss the view controller ourselves
    NSLog(@"Did finish modal presentation");

    [_selections enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if ([obj boolValue])
        {
            ALAsset  *asset         = [self.assets objectAtIndex:idx];
            UIImage  *image         = nil;
            UIImage  *thumnailImage = nil;
            NSString *fileId        = nil;

            fileId = [[[asset valueForProperty:ALAssetPropertyAssetURL] absoluteString] md5String];

            NSString *fileName         = [NSString filePathInDocumentWithFileName:fileId];
            NSString *thumnailFileName = [NSString filePathInDocumentWithFileName:[fileId stringByAppendingString:@"-thumnail"]];

            image         = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
            thumnailImage = [(MWPhoto *) [self.thumbs objectAtIndex:idx] image];

//            [self writeImage:image
//                  toFilePath:fileName];
//            [self writeImage:thumnailImage
//                  toFilePath:thumnailFileName];

            PhotoEntity *photoEntity = [[PhotoEntity alloc] init];
            photoEntity.imageId                 = fileId;
            photoEntity.imageUrlString          = fileName;
            photoEntity.image                   = image;
            photoEntity.thumbnailImageUrlString = thumnailFileName;
            photoEntity.thumbnailImage          = thumnailImage;

            [self.selectedPhotoMArray addObject:photoEntity];
        }
        else
        {

        }


    }];
    [self reloadPhotoItemView:self.selectedPhotoMArray];
    [photoBrowser dismissViewControllerAnimated:YES
                                     completion:nil];
}

#pragma mark - Load Assets

- (void)loadAssets
{

    // Initialise
    self.assets       = [NSMutableArray new];
    self.assetLibrary = [[ALAssetsLibrary alloc] init];

    // Run in the background as it takes a while to get all assets from the library
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^
    {

        NSMutableArray *assetGroups          = [[NSMutableArray alloc] init];
        NSMutableArray *assetURLDictionaries = [[NSMutableArray alloc] init];

        // Process assets
        void (^assetEnumerator)(ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop)
        {
            if (result != nil)
            {
                if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto])
                {
                    [assetURLDictionaries addObject:[result valueForProperty:ALAssetPropertyURLs]];
                    NSURL *url = result.defaultRepresentation.url;
                    [_assetLibrary assetForURL:url
                                   resultBlock:^(ALAsset *asset) {
                        if (asset)
                        {
                            @synchronized (_assets)
                            {
                                [_assets addObject:asset];
//                                if (_assets.count == 1) {
//                                    // Added first asset so reload data
//                                    [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
//                                }
                            }
                        }
                    }
                                  failureBlock:^(NSError *error){
                        NSLog(@"operation was not successfull!");
                    }];

                }
            }
        };

        // Process groups
        void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop)
        {
            if (group != nil)
            {
                [group enumerateAssetsWithOptions:NSEnumerationReverse
                                       usingBlock:assetEnumerator];
                [assetGroups addObject:group];
            }
        };

        // Process!
        [self.assetLibrary enumerateGroupsWithTypes:ALAssetsGroupAll
                                         usingBlock:assetGroupEnumerator
                                       failureBlock:^(NSError *error) {
            NSLog(@"There is an error");
        }];

    });

}


@end
